<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询文件名" v-model="searchFilename"></el-input>
      <el-button type="primary" @click="loadFiles(1)">查询</el-button>
      <el-button type="info" @click="resetSearch">重置</el-button>
    </div>
    <div style="margin: 10px 0">
</el-upload>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="danger" plain @click="delBatch">批量下载</el-button>
    </div>
    <el-table :data="filesData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="fileid" label="文件 ID" width="70" align="center"></el-table-column>
      <el-table-column prop="filename" label="文件名"></el-table-column>
      <el-table-column prop="filesize" label="文件大小"></el-table-column>
      <el-table-column prop="uploaderid" label="上传者 ID"></el-table-column>
      <el-table-column prop="name" label="上传者名字"></el-table-column>
      <el-table-column prop="uploaddate" label="上传时间"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="danger" plain @click="del(scope.row.fileid)">删除</el-button>
          <el-button size="mini" type="success" plain @click="downloadFile(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: "Files",
  data() {
    return {
      filesData: [],  // 所有的文件数据
      pageNum: 1,    // 当前的页码
      pageSize: 10,  // 每页显示的个数
      searchFilename: '',
      total: 0,
      dialogVisible: false,
      currentUserId: '',
      form: {},
      fileList: [],
      ids: [],
   user: JSON.parse(localStorage.getItem('user') || '{}'),
      rules: {
      }
    };
  },
  methods: {
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据');
        return;
      }
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.post('/files/delete/batch',this.ids ).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功');
            this.loadFiles(1);
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {});
    },
    // 获取上传者名字
    //TODO: 待优化
    async fetchName(Id) {
      try {
        const res = await this.$request.get(`/users/selectNameById/${Id}`);
        console.log('获取上传者名字', res.data); 
        return res.data;
      } catch (error) {
        console.error('获取上传者名字失败', error);
        return null;
      }
    },

    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.fileid);
    },
    del(fileid) {
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.delete('/files/delete/' + fileid).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功');
            this.loadFiles(1);
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {});
    },
    downloadFile(row) {
      // 假设row.fileid是文件ID
      const fileId = row.fileid; // 获取文件ID
      const downloadUrl = `http://localhost:9091/files/download/${encodeURIComponent(fileId)}`; // 构建下载URL
      window.open(downloadUrl, '_blank'); // 使用_blank打开新标签页下载
    },
    resetSearch() {
      this.searchFilename = '';
      this.loadFiles();
    },

    handleCurrentChange(pageNum) {
      this.loadFiles(pageNum);
    },

    async loadFiles(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      try {
        const res = await this.$request.get('/files/selectByPage', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            filename: this.searchFilename
          }
        });
        this.filesData = res.data.records || [];
        this.total = res.data.total || 0;

        // 获取上传者名字
        for (let i = 0; i < this.filesData.length; i++) {
          const uploaderId = this.filesData[i].uploaderid;
          const uploaderName = await this.fetchName(uploaderId);
          this.$set(this.filesData[i], 'name', uploaderName);
        }

      } catch (error) {
        console.error('请求文件数据失败', error);
        this.filesData = [];
        this.total = 0;
        this.$message.error('加载文件数据失败');
      }
    },

    getToken() {
      return localStorage.getItem('token');
    }
  },
  created() {
    this.loadFiles();
  },
};
</script>

<style scoped>

</style>